package com.fr.web.core.service;

import com.fr.base.CodeUtils;
import com.fr.base.ColumnRow;
import com.fr.base.FRContext;
import com.fr.base.Inter;
import com.fr.base.Painter;
import com.fr.base.StringUtils;
import com.fr.base.core.BaseCoreUtils;
import com.fr.base.core.ComparatorUtils;
import com.fr.base.core.FRCoreContext;
import com.fr.base.core.RSADecode;
import com.fr.base.core.html.Html;
import com.fr.base.core.html.Tag;
import com.fr.base.core.json.JSONArray;
import com.fr.base.core.json.JSONException;
import com.fr.base.core.json.JSONObject;
import com.fr.base.core.util.vt.VT4FR;
import com.fr.base.core.util.vt.VT4FR.FUNC;
import com.fr.report.CellElement;
import com.fr.report.FloatElement;
import com.fr.report.Report;
import com.fr.report.ReportSettings;
import com.fr.report.ResultReport;
import com.fr.report.ResultWorkBook;
import com.fr.report.cellElement.Formula;
import com.fr.report.cellElement.Present;
import com.fr.report.cellElement.core.CellElementAttribute;
import com.fr.report.cellElement.core.CellUtils;
import com.fr.report.core.DynamicValueList;
import com.fr.report.core.FormException;
import com.fr.report.core.FormReport;
import com.fr.report.core.ReportHelper;
import com.fr.report.core.ReportUtils;
import com.fr.report.io.ExcelImporter;
import com.fr.report.js.NameJavaScriptGroup;
import com.fr.report.script.Calculator;
import com.fr.report.write.ValueVerifier;
import com.fr.util.Consts;
import com.fr.web.Browser;
import com.fr.web.ErrorHandler;
import com.fr.web.Repository;
import com.fr.web.core.Attachment;
import com.fr.web.core.ErrorHandlerHelper;
import com.fr.web.core.HTMLWriter;
import com.fr.web.core.HTMLWriterUtils;
import com.fr.web.core.ReportBackgroundDimension;
import com.fr.web.core.Service;
import com.fr.web.core.SessionIDInfor;
import com.fr.web.core.WebUtils;
import com.fr.web.core.chwriter.WriteCellWriter;
import com.fr.web.core.upload.SmartFile;
import com.fr.web.core.upload.SmartFiles;
import com.fr.web.core.upload.SmartUpload;
import java.awt.Dimension;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WriteService
  implements Service
{
  private static boolean supportWrite = true;
  private static WriteService WRITE_SERVICE;

  public static WriteService getInstance()
  {
    return WRITE_SERVICE;
  }

  public boolean accept(String paramString)
  {
    return paramString.startsWith("write_");
  }

  public void process(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString1, String paramString2)
    throws Exception
  {
    if (!(supportWrite))
    {
      localObject = WebUtils.createPrintWriter(paramHttpServletResponse);
      ((PrintWriter)localObject).print("This edition dosen't support write, please buy a enterprise edition!");
      ((PrintWriter)localObject).flush();
      ((PrintWriter)localObject).close();
      return;
    }
    Object localObject = SessionDealWith.getSessionIDInfor(paramString2);
    if (localObject == null)
    {
      ErrorHandlerHelper.getErrorHandler().error(paramHttpServletRequest, paramHttpServletResponse, "Reportlet SessionID: \"" + paramString2 + "\" time out.");
      return;
    }
    if ("write_content".equals(paramString1))
    {
      readContent((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_appendrcdata".equals(paramString1))
    {
      InsertUpdateService.simpleInsertRecord((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_appenddata".equals(paramString1))
    {
      InsertUpdateService.insertRecord((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_deletercdata".equals(paramString1))
    {
      InsertUpdateService.simpleDeleteRecord((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_deletedata".equals(paramString1))
    {
      InsertUpdateService.smartDeleteRecord((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_undeletedata".equals(paramString1))
    {
      InsertUpdateService.smartUnDeleteRecord((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_calculate".equals(paramString1))
    {
      calculate(paramHttpServletRequest, paramHttpServletResponse, (SessionIDInfor)localObject);
    }
    else if ("write_verify".equalsIgnoreCase(paramString1))
    {
      checkValueVerify((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_present".equalsIgnoreCase(paramString1))
    {
      present((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
    else if ("write_saveContent".equalsIgnoreCase(paramString1))
    {
      saveContent(paramHttpServletResponse);
    }
    else if ("write_writeContent".equalsIgnoreCase(paramString1))
    {
      submitReport((SessionIDInfor)localObject, paramHttpServletResponse);
    }
    else
    {
      if ("write_undoContent".equalsIgnoreCase(paramString1))
        return;
      if ("write_importExcelData".equalsIgnoreCase(paramString1))
        importExcelData((SessionIDInfor)localObject, paramHttpServletRequest, paramHttpServletResponse);
    }
  }

  private static void submitReport(SessionIDInfor paramSessionIDInfor, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    int i = 1;
    try
    {
      paramSessionIDInfor.submit();
    }
    catch (FormException localFormException)
    {
      FRContext.getLogger().log(Level.WARNING, localFormException.getMessage(), localFormException);
      i = 0;
    }
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    localPrintWriter.print((i != 0) ? "success" : "failure");
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void readContent(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    int i = Integer.parseInt(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "reportIndex"));
    Report localReport = paramSessionIDInfor.getReport2Show(i);
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    writeReportPane(localPrintWriter, localReport, i, new Repository(paramHttpServletRequest, paramSessionIDInfor));
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void writeReportPane(PrintWriter paramPrintWriter, Report paramReport, int paramInt, Repository paramRepository)
  {
    Tag localTag1 = new Tag("div");
    localTag1.css("position", "absolute").cls("sheet-container");
    if (paramRepository.getBrowser().shouldSetOverflowAsHiddenOnSheetContainer())
      localTag1.css("overflow", "hidden");
    HTMLWriter localHTMLWriter = HTMLWriter.getInstance();
    if ((paramReport.getReportSettings() != null) && (paramReport.getReportSettings().getWriteFrozenColumnRow() != null))
    {
      localObject1 = (ColumnRow[])((FormReport)paramReport).getExtendedColumnRowList(new ColumnRow[] { paramReport.getReportSettings().getWriteFrozenColumnRow() }, null).get(0);
      localHTMLWriter.writeFrozenContent(localTag1, paramReport, localObject1[0], paramInt, new WriteCellWriter(paramInt, paramRepository), paramRepository);
    }
    else
    {
      localObject1 = localHTMLWriter.writeJSReport(paramReport, paramInt, new WriteCellWriter(paramInt, paramRepository), paramRepository);
      localObject2 = ReportHelper.getColumnWidthList(paramReport);
      localObject3 = ReportHelper.getRowHeightList(paramReport);
      int i = Math.max(((DynamicValueList)localObject2).getRangeValueFromZero(paramReport.getColumnCount()), 1);
      int j = Math.max(((DynamicValueList)localObject3).getRangeValueFromZero(paramReport.getRowCount()), 1);
      localTag4 = new Tag("div");
      HTMLWriterUtils.writeBackground(localTag4, ReportUtils.getReportSettings(paramReport).getBackground(), new ReportBackgroundDimension(i + 5, j + 5), false, paramRepository, false);
      localTag4.sub((Html)localObject1);
      localTag1.sub(localTag4);
      Iterator localIterator = paramReport.floatIterator();
      while (localIterator.hasNext())
      {
        FloatElement localFloatElement = (FloatElement)localIterator.next();
        Object localObject4 = null;
        NameJavaScriptGroup localNameJavaScriptGroup = localFloatElement.getNameHyperlinkGroup();
        if ((localNameJavaScriptGroup != null) && (localNameJavaScriptGroup.size() > 0))
        {
          localObject4 = new Tag("span");
          String str = "{}";
          try
          {
            str = HTMLWriterUtils.writeJSLinkContent(localNameJavaScriptGroup, paramRepository);
          }
          catch (JSONException localJSONException)
          {
            FRContext.getLogger().log(Level.WARNING, localJSONException.getMessage(), localJSONException);
          }
          ((Tag)localObject4).attr("onclick", "FR.doHyperlink(event ||window.event," + str + ")");
          ((Tag)localObject4).css("cursor", "pointer");
        }
        int k = ((DynamicValueList)localObject2).getRangeValueFromZero(localFloatElement.getColumn()) + localFloatElement.getLeftDistance();
        int l = ((DynamicValueList)localObject3).getRangeValueFromZero(localFloatElement.getRow()) + localFloatElement.getTopDistance();
        int i1 = localFloatElement.getSize().width + 1;
        int i2 = localFloatElement.getSize().height + 1;
        i = Math.max(i, k + i1);
        j = Math.max(j, l + i2);
        Tag localTag5 = new Tag("div");
        if (localObject4 == null)
          localObject4 = localTag5;
        else
          ((Tag)localObject4).sub(localTag5);
        localTag4.sub((Html)localObject4);
        localTag5.css("overflow", "hidden");
        localTag5.css("position", "absolute");
        localTag5.css("left", k + "px");
        localTag5.css("top", l + "px");
        localTag5.css("width", i1 + "px");
        localTag5.css("height", i2 + "px");
        localTag5.sub(localFloatElement.toTag(paramRepository));
      }
      localTag4.css("width", (i + 5) + "px").css("height", (j + 5) + "px");
    }
    Object localObject1 = new Tag("div");
    Object localObject2 = new Tag("div");
    Object localObject3 = new Tag("div");
    Tag localTag2 = new Tag("div");
    Tag localTag3 = new Tag("div");
    localTag1.sub((Html)localObject1);
    localTag1.sub((Html)localObject2);
    localTag1.sub((Html)localObject3);
    localTag1.sub(localTag2);
    localTag1.sub(localTag3);
    ((Tag)localObject1).cls("fDtop");
    ((Tag)localObject2).cls("fDleft");
    ((Tag)localObject3).cls("fDbottom");
    localTag2.cls("fDright");
    localTag3.cls("fDdot");
    ((Tag)localObject1).sub(paramRepository.checkoutImageTag(null, 1, 1).css("display", "none"));
    ((Tag)localObject2).sub(paramRepository.checkoutImageTag(null, 1, 1).css("display", "none"));
    ((Tag)localObject3).sub(paramRepository.checkoutImageTag(null, 1, 1).css("display", "none"));
    localTag2.sub(paramRepository.checkoutImageTag(null, 1, 1).css("display", "none"));
    localTag3.sub(paramRepository.checkoutImageTag(null, 5, 5));
    Tag localTag4 = new Tag("div");
    localTag1.sub(localTag4);
    localTag4.cls("x-editor").css("position", "absolute").css("display", "none").css("z-index", "4").css("padding-left", "0px");
    localTag1.writeHtml(paramPrintWriter);
  }

  private static void saveContent(HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    localPrintWriter.print("success");
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void checkValueVerify(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    JSONArray localJSONArray = null;
    int i = 0;
    int j = paramSessionIDInfor.getWorkBook2Show().getReportCount();
    while (i < j)
    {
      ValueVerifier[] arrayOfValueVerifier;
      int k;
      ResultReport localResultReport = paramSessionIDInfor.getWorkBook2Show().getResultReport(i);
      if (localResultReport instanceof FormReport)
      {
        localResultReport.recalculate(paramSessionIDInfor.getParameterMap4Execute());
        FormReport localFormReport = (FormReport)localResultReport;
        arrayOfValueVerifier = localFormReport.checkValueVerifiers();
        for (k = 0; k < arrayOfValueVerifier.length; ++k)
        {
          ValueVerifier localValueVerifier = arrayOfValueVerifier[k];
          int l = localValueVerifier.getType();
          if (l == 0)
            break label193:
          if (localJSONArray == null)
            localJSONArray = new JSONArray();
          JSONObject localJSONObject = new JSONObject();
          localJSONArray.put(localJSONObject);
          localJSONObject.put("formula", localValueVerifier.getFormula().getContent().substring(1));
          if (l == 1)
            localJSONObject.put("message", localValueVerifier.getMessage());
          else if (l == 2)
            localJSONObject.put("message", Inter.getLocText("Verify-Formular_Parser_Error"));
        }
      }
      label193: ++i;
    }
    if ((localJSONArray != null) && (localJSONArray.length() > 0))
    {
      PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
      localJSONArray.write(localPrintWriter);
      localPrintWriter.flush();
      localPrintWriter.close();
    }
  }

  private static void importExcelData(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    ServletContext localServletContext = paramHttpServletRequest.getSession().getServletContext();
    SmartUpload localSmartUpload = new SmartUpload();
    localSmartUpload.initialize(localServletContext, paramHttpServletRequest, paramHttpServletResponse);
    localSmartUpload.upload();
    SmartFiles localSmartFiles = localSmartUpload.getFiles();
    if (localSmartFiles.getSize() == 0L)
      return;
    SmartFile localSmartFile = localSmartFiles.getFile(0);
    String str = localSmartFile.getContentType();
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    if ((StringUtils.isBlank(str)) || (!(localSmartFile.getFileName().endsWith(".xls"))))
    {
      localPrintWriter.write("typewrong");
      localPrintWriter.flush();
      localPrintWriter.close();
      return;
    }
    ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(localSmartFile.getBytes());
    try
    {
      ExcelImporter.importExcel2Book(paramSessionIDInfor.getWorkBook2Show(), paramSessionIDInfor.getContextBook(), localByteArrayInputStream, paramSessionIDInfor.getParameterMap4Execute());
      localPrintWriter.write("success");
    }
    catch (Exception localException)
    {
      localPrintWriter.write("wrong");
    }
    finally
    {
      localPrintWriter.flush();
      localPrintWriter.close();
      localByteArrayInputStream.close();
    }
  }

  private static void calculate(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, SessionIDInfor paramSessionIDInfor)
    throws Exception
  {
    Object localObject;
    String str1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "ptype");
    String str2 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "pcontent");
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    Object[] arrayOfObject = new Object[1];
    if ("parameter".equals(str1))
    {
      localObject = paramSessionIDInfor.getParameterValue(str2);
      arrayOfObject[0] = CodeUtils.object2JSONable(localObject);
    }
    else if ("expression".equals(str1))
    {
      localObject = Calculator.createCalculator();
      ((Calculator)localObject).setCurrentTableDataSource(paramSessionIDInfor.getContextBook());
      arrayOfObject[0] = CodeUtils.object2JSONable(((Calculator)localObject).eval(str2));
    }
    new JSONArray(arrayOfObject).write(localPrintWriter);
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void present(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    ResultWorkBook localResultWorkBook = paramSessionIDInfor.getWorkBook2Show();
    int i = StringUtils.stringToInt(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "rptIdx"), -1);
    int j = StringUtils.stringToInt(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "col"), -1);
    int k = StringUtils.stringToInt(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "row"), -1);
    if ((i < 0) || (localResultWorkBook.getReportCount() <= i) || (j < 0) || (k < 0))
      return;
    Report localReport = localResultWorkBook.getReport(i);
    CellElement localCellElement = localReport.getCellElement(j, k);
    if (localCellElement == null)
      return;
    Present localPresent = localCellElement.getPresent();
    if (localPresent == null)
      return;
    Calculator localCalculator = Calculator.createStaticCalculator();
    localCalculator.setCurrentReport(localReport);
    localCalculator.setCurrentTableDataSource(paramSessionIDInfor.getContextBook());
    localCalculator.setCurrentColumnRow(ColumnRow.valueOf(j, k));
    Object localObject = localPresent.present(CodeUtils.jsonDecode(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "value")), localCalculator);
    localCalculator.release();
    localCellElement.setAttribute(CellElementAttribute.PRESENT_VALUE, localObject);
    if ((localObject instanceof Image) || (localObject instanceof Painter))
    {
      int l = 0;
      int i1 = localCellElement.getRow();
      int i2 = localCellElement.getRowSpan() + localCellElement.getRow();
      while (i1 < i2)
      {
        l += localReport.getRowHeight(i1);
        ++i1;
      }
      i1 = 0;
      i2 = localCellElement.getColumn();
      int i3 = localCellElement.getColumnSpan() + localCellElement.getColumn();
      while (i2 < i3)
      {
        i1 += localReport.getColumnWidth(i2);
        ++i2;
      }
      Image localImage = CellUtils.value2Image(localObject, localCellElement.getStyle(), i1, l);
      Attachment localAttachment = AttachmentService.addAttachment(localImage);
      localObject = localAttachment.toConfig();
    }
    if (localObject != null)
    {
      PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
      localPrintWriter.print(CodeUtils.jsonEncode(localObject));
      localPrintWriter.flush();
      localPrintWriter.close();
    }
  }

  static
  {
    byte[] arrayOfByte = FRCoreContext.getBytes();
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    try
    {
      RSADecode.decode(arrayOfByte, localByteArrayOutputStream);
    }
    catch (Exception localException1)
    {
    }
    try
    {
      JSONObject localJSONObject = new JSONObject(new String(localByteArrayOutputStream.toByteArray(), "UTF-8"));
      supportWrite = (localJSONObject.getLong("deadline") > Calendar.getInstance().getTimeInMillis()) && (localJSONObject.has("version")) && (ComparatorUtils.equals(Consts.VERSION, localJSONObject.getString("version"))) && (((localJSONObject.getLong("deadline") - Calendar.getInstance().getTimeInMillis() < 3153600000L) || ((localJSONObject.has("macaddress")) && (BaseCoreUtils.getMacAddresses().contains(localJSONObject.getString("macaddress")))))) && (VT4FR.ONLINE_WRITE.support());
    }
    catch (Exception localException2)
    {
    }
    WRITE_SERVICE = new WriteService();
  }
}